package com.sann.eduservice.controller;


import com.sann.common.utils.R;
import com.sann.eduservice.entity.chapter.Chapter;
import com.sann.eduservice.entity.chapter.vo.ChapterVO;
import com.sann.eduservice.service.ChapterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程大纲章节 前端控制器
 * </p>
 *
 * @author zjw
 * @since 2021-04-17
 */
@Api(tags = "章节管理")
@RestController
@RequestMapping("/eduservice/chapter/")
@CrossOrigin
public class ChapterController {

    @Autowired
    private ChapterService chapterService;


    @ApiOperation(value = "获取课程大纲列表,根据课程id进行查询")
    @GetMapping(value = "getList/{courseId}")
    public R getList(@PathVariable("courseId") String courseId){
        List<ChapterVO> tree = this.chapterService.getList(courseId);
        if (CollectionUtils.isEmpty(tree)) {
            return R.ok().data("courseId", courseId).msg("获取到的数据为空");
        }
        return R.ok().data("tree", tree);
    }

    @ApiOperation(value = "添加章节")
    @PostMapping(value="save")
    public R save(@RequestBody Chapter chapter){
        boolean bol = this.chapterService.save(chapter);
        if (bol) {
//            return R.ok().data("chapter",chapter);
            return R.ok();
        }else{
//            return R.error().data("chapter", chapter).msg("添加章节失败");
            return R.error();
        }
    }

    @ApiOperation(value = "根据章节ID查询")
    @GetMapping(value = "getById/{chapterId}")
    public R getById(@PathVariable("chapterId") String chapterId){
        Chapter chapter = this.chapterService.getById(chapterId);
        return R.ok().data("chapter", chapter);
    }

    @ApiOperation(value = "修改章节", notes = "根据 chapter包含有ID来修改")
    @PostMapping(value = "update")
    public R update(@RequestBody Chapter chapter){
        boolean bol = this.chapterService.updateById(chapter);
        if (bol) {
            return R.ok().data("chapter", chapter).msg("修改章节成功");
        }else{
            return R.error().msg("修改章节失败");
        }
    }

    @ApiOperation("删除章节")
    @DeleteMapping(value="deleteById/{chapterId}")
    public R deleteById(@PathVariable("chapterId") String chapterId){
//        boolean bol = this.chapterService.removeById(chapterId);
        boolean bol = this.chapterService.deleteById(chapterId);
        if (!bol) {
            return R.error().msg("删除章节失败");
        }
        return R.ok();
    }
}

